package com.grace.cms.general.taglib;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import com.grace.redis.utils.RedisCache;
import com.grace.cms.common.domain.entity.CmsLink;
import com.grace.cms.general.cache.GeneralLinkCacheService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("linkTag")
public class LinkTag {
  @Autowired
  private GeneralLinkCacheService cmsLinkService;

  @Autowired
    private RedisCache redisCache;


     /**
   * 获取链接通过ID
   * 
   * @param linkId
   * @return
   */
  public CmsLink selectCmsLinkById(long linkId) {
    return cmsLinkService.selectCmsLinkById(linkId);
  }

  /**
   * 获取链接列表
   * 
   * @param parentId 父亲节点
   * @param nodeType 节点类型
   * @return
   */
  public List<CmsLink> listLinks(long parentId, String nodeType) {
    return this.listCmsLinkBy(parentId,nodeType, null);
  }

  public List<CmsLink> listLinkOrderByParentId(Long parentId, Long orderNum) {

    return this.listCmsLinkBy(parentId,null, orderNum);
  }

  public List<CmsLink> listLinkOrderByNodeType(String nodeType, Long orderNum) {

    return this.listCmsLinkBy(null,nodeType, orderNum);
  }


    public List<CmsLink> linkTree(long parentId, String nodeType) {
      return this.buildLinkTree(parentId, this.listCmsLinkBy(null, nodeType, null));
  }
  /**
   * 
   * @param parentId
   * @param nodeType
   * @return
   */
  private List<CmsLink> buildLinkTree(long parentId, List<CmsLink> treeList) {
        List<CmsLink> list = new ArrayList<>();
        Optional.ofNullable(treeList).orElse(new ArrayList<>())
                .stream()
                // 第一次筛选出主父节点列表进入循环，循环里面 进入递归 筛选出递归传递的从父节点列表
                .filter(root -> root.getParentId().equals(parentId))
                // 递归，最末的父节点从整个列表筛选出它的子节点列表依次组装
                .forEach(tree -> {
                    List<CmsLink> children = this.buildLinkTree(tree.getLinkId(), treeList);
                    tree.setChildren(children);
                    list.add(tree);
                });
        return list;
  }


   private List<CmsLink> listCmsLinkBy(Long parentId, String nodeType, Long orderNum) {
    
        // 尝试从缓存中获取栏目数据
        List<Long> linkIds = cmsLinkService.listCmsLinks(parentId, nodeType, orderNum);
        ArrayList<Object> categoryIdObjects = new ArrayList<>(linkIds.stream()
                .map(Object::toString)
                .collect(Collectors.toList()));
        List<CmsLink> links = redisCache.getMultiCacheMapValue(GeneralLinkCacheService.allKeyPrefix, categoryIdObjects);
        if (links.stream().anyMatch(link -> link == null)) {
            return filterListNull(links, linkIds,parentId, nodeType, orderNum);
        }
        else {
            return links;
        }

    }

    private List<CmsLink> filterListNull(List<CmsLink> links, List<Long> linkIds,Long parentId, String nodeType, Long orderNum) {
        // 创建一个新的列表用于保存非空的 CmsLink 项
        List<CmsLink> nonNullLinks = new ArrayList<>();
        for (int i = 0; i < linkIds.size(); i++) {
            if (links.get(i) != null) {
                nonNullLinks.add(links.get(i));
            } else {
                CmsLink cmsLink = cmsLinkService.selectCmsLinkById(linkIds.get(i));
                if (cmsLink != null) {
                    redisCache.setCacheMapValue(GeneralLinkCacheService.allKeyPrefix,
                            Long.toString(cmsLink.getLinkId()), cmsLink);
                    nonNullLinks.add(cmsLink);
                } else {

                }
            }
        }
        return nonNullLinks;
    }




}
